﻿using YNTK.Common.Enum;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.LinqBuilder;
using YNTK.System.Entitys.Dto.System.SysLog;
using YNTK.System.Entitys.System;
using YNTK.System.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using YNTK.Data.MongoDB.Repositorie;
using MongoDB.Driver;
using System.Linq;
using System.Security.Claims;
using YNTK.Common.Const;

namespace YNTK.System.Service.System
{
    /// <summary>
    /// 系统日志
    /// 版 本：V1.0.0
    /// 版 权：云南通科科技有限公司（https://www.yntkkj.com）
    /// 作 者：李仕鹏
    /// 日 期：2021-06-01 
    /// </summary>
    [ApiDescriptionSettings(Tag = "系统日志", Name = "Log", Order = 788)]
    [Route("api/system/[controller]")]
    public class SysLogService : ISysLogService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<SysLogEntity> _sysLogRepository;//系统日志仓储
        private readonly IMongoDBRepository<SysLogEntity> _sysLogMongoDbRepository;//系统日志mongodb仓储

        private readonly string _syslogs = "base_syslogs";//mongodb中系统日志数据集名称

        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="sysLogRepository">系统日志仓储</param>
        /// <param name="sysLogMongoDbRepository">系统日志mongodb仓储</param>
        public SysLogService(ISqlSugarRepository<SysLogEntity> sysLogRepository,
            IMongoDBRepository<SysLogEntity> sysLogMongoDbRepository)
        {
            _sysLogRepository = sysLogRepository;
            _sysLogMongoDbRepository = sysLogMongoDbRepository;
        }

        #region GET

        /// <summary>
        /// 分页获取系统日志列表数据
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("{Type}")]
        public async Task<dynamic> GetList([FromQuery] LogListQuery input)
        {
            var userContext = App.User;
            string userId = userContext?.FindFirstValue(ClaimConst.CLAINM_USERID);
            string organizeId = userContext?.FindFirstValue(ClaimConst.ORGANIZEID);
            string mechanismId = userContext?.FindFirstValue(ClaimConst.MECHANISMID);
            if (string.IsNullOrWhiteSpace(organizeId)) organizeId = "org00000000";

            #region 拼接查询条件
            var whereLambda = LinqExpression.And<SysLogEntity>();
            whereLambda = whereLambda.And(x => x.Category == input.type.GetHashCode() && x.OrganizeId== organizeId);     
            if(input.endTime != null && input.startTime != null)
                whereLambda = whereLambda.And(x => SqlFunc.Between(x.CreatorTime, input.startTime, input.endTime));
            else
            {
                if (input.startTime != null) whereLambda = whereLambda.And(x => x.CreatorTime >= input.startTime);
                if (input.endTime != null) whereLambda = whereLambda.And(x => x.CreatorTime <= input.endTime);
            }
            if(!string.IsNullOrEmpty(input.keyword))
                whereLambda = whereLambda.And(m => m.UserName.Contains(input.keyword) || 
                m.IPAddress.Contains(input.keyword) || m.ModuleName.Contains(input.keyword));
            #endregion

            var data = new SqlSugarPagedList<SysLogEntity>();
            #region 从mongodb中获取访客记录数据
            //排序生成器
            var builderSort = Builders<SysLogEntity>.Sort;
            //排序约束   Ascending 正序    Descending 倒序
            var sort = builderSort.Descending(r => r.CreatorTime);
            //Item1.结果集 Item2.总条数 Item3.总页数
            (List<SysLogEntity>, int, int) result =
                await _sysLogMongoDbRepository.GetListAsync(_syslogs,
                whereLambda, input.currentPage, input.pageSize, null, sort);
            data.list = result.Item1;
            data.pagination = new PagedModel()
            {
                PageIndex = input.currentPage,
                PageSize = input.pageSize,
                Total = result.Item2,
                PageCount = result.Item3
            };
            #endregion

            if (data.list == null || data.list.Count() <= 0)
            {
                #region 从sqlserver数据库中获取系统日志数据
                var sqlResult = await _sysLogRepository.Entities.Where(whereLambda)
                     .OrderBy(r => r.CreatorTime, OrderByType.Desc)
                     .ToPagedListAsync(input.currentPage, input.pageSize);
                data.list = sqlResult.list;
                data.pagination = sqlResult.pagination;
                #endregion
            }

            if (data.list == null || data.list.Count() <= 0) return null;
            switch (input.type)
            {
                case SysLogTypeEnum.LoginLog://登录日志
                    var loginPage = new SqlSugarPagedList<LogLoginOutput>()
                    {
                        list = data.list.Adapt<List<LogLoginOutput>>(),
                        pagination = data.pagination
                    };
                    return TkPageResult<LogLoginOutput>.SqlSugarPageResult(loginPage);
                case SysLogTypeEnum.AccessLog://访问日志
                    break;
                case SysLogTypeEnum.OperationLog://操作日志
                    break;
                case SysLogTypeEnum.AbnormalLog://异常日志
                    var abnormalPage = new SqlSugarPagedList<LogExceptionOutput>()
                    {
                        list = data.list.Adapt<List<LogExceptionOutput>>(),
                        pagination = data.pagination
                    };
                    return TkPageResult<LogExceptionOutput>.SqlSugarPageResult(abnormalPage);
                case SysLogTypeEnum.RequestLog://请求日志
                    var requestPage = new SqlSugarPagedList<LogRequestOutput>()
                    {
                        list = data.list.Adapt<List<LogRequestOutput>>(),
                        pagination = data.pagination
                    };
                    return TkPageResult<LogRequestOutput>.SqlSugarPageResult(requestPage);
                default:
                    break;
            }
            return null;
        }

        #endregion

        #region POST

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task Delete([FromBody] LogDelInput input)
        {
            try
            {
                //开启事务
                _sysLogRepository.Ado.BeginTran();

                await _sysLogMongoDbRepository.DeleteAsync(_syslogs,m=>input.ids.Contains(m.Id));
                await _sysLogRepository.DeleteAsync(input.ids);

                _sysLogRepository.Ado.CommitTran();
            }
            catch (Exception)
            {
                _sysLogRepository.Ado.RollbackTran();
                throw YNTKException.Oh(ErrorCode.COM1001);
            }
        }

        #endregion
    }
}
